import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:mobile_scanner/mobile_scanner.dart';

import '../../config/color_config.dart';
import '../../config/string_config.dart';
import '../../widgets/title/title_widget.dart';
import '../permission/permission_manager.dart';


class QRCodeScannerPage extends StatefulWidget {
  const QRCodeScannerPage({Key? key}) : super(key: key);

  @override
  State<QRCodeScannerPage> createState() => _QRCodeScannerPageState();
}

class _QRCodeScannerPageState extends State<QRCodeScannerPage> with WidgetsBindingObserver {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  // 创建导航键用于管理页面导航
  final GlobalKey<NavigatorState> _navigatorKey = GlobalKey<NavigatorState>();
  MobileScannerController? _controller;
  bool _hasPermission = false;
  bool _isScanning = true;


  @override
  void initState() {
    super.initState();
    // 添加WidgetsBinding观察者
    WidgetsBinding.instance.addObserver(this);
    _checkPermission();
  }


  Future<void> _checkPermission() async {
    bool hasPermission = await PermissionManager.requestCameraPermission();
    setState(() {
      _hasPermission = hasPermission;
    });
    if (hasPermission) {
      _controller = MobileScannerController();
    }
  }

  @override
  void dispose() {
    _controller?.dispose();
    // 移除WidgetsBinding观察者
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  void _handleDetection(BarcodeCapture capture) async {
    if (!mounted) return;
    if (!_isScanning) return;
    
    final List<Barcode> barcodes = capture.barcodes;
    for (final barcode in barcodes) {
      if (barcode.rawValue != null) {
        setState(() {
          _isScanning = false;
        });
        
        // 只停止扫描，不调用dispose
        await _controller?.stop();
        
        // 返回结果
        if (mounted) {
          Navigator.of(context).pop(barcode.rawValue);
        }
        break;
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    if (!_hasPermission) {
      return MaterialApp(
          navigatorKey: _navigatorKey,
          home:Scaffold(
            key: _scaffoldKey,
        appBar: TitleWidget(context: context, scaffoldKey: _scaffoldKey),
        body: const Center(
          child: Text(StringConfig.camera_permission_denied),
        ),
      )
      );
    }

    return PopScope(
      canPop: false,
        child: Scaffold(
      appBar: AppBar(
        title: Text(StringConfig.scan_qr_code),
        backgroundColor: ColorConfig.title_back,
        actions: [
          IconButton(
            icon: ValueListenableBuilder(
              valueListenable: _controller!.torchState,
              builder: (context, state, child) {
                switch (state) {
                  case TorchState.off:
                    return const Icon(Icons.flash_off);
                  case TorchState.on:
                    return const Icon(Icons.flash_on);
                }
              },
            ),
            onPressed: () => _controller?.toggleTorch(),
          ),
        ],
      ),
      body: _isScanning ? MobileScanner(
        controller: _controller,
        onDetect: _handleDetection,
      ) : const Center(
        child: CircularProgressIndicator(),
      ),
    ), onPopInvoked :  (didPop)async{
      print("返回了");
      Navigator.pop(context);
    });
  }
} 